import { createI18n } from 'vue-i18n'
import cz from './locales/cz.json'
import de from './locales/de.json'
import en from './locales/en.json'
import es from './locales/es.json'
import fr from './locales/fr.json'
import gr from './locales/gr.json'
import hu from './locales/hu.json'
import id from './locales/id.json'
import it from './locales/it.json'
import jp from './locales/jp.json'
import kr from './locales/kr.json'
import my from './locales/my.json'
import nl from './locales/nl.json'
import pt from './locales/pt.json'
import ru from './locales/ru.json'
import sa from './locales/sa.json'
import th from './locales/th.json'
import tr from './locales/tr.json'
import ua from './locales/ua.json'
import vn from './locales/vn.json'
import zh from './locales/zh.json'
import zh1 from './locales/zh1.json'
import encrypt from '../utils/encrypt.js'
import { nextTick } from 'vue'

// 预定义已加载的语言包
const loadedLanguages = ['en', 'zh', 'jp', 'kr', 'es', 'fr', 'pt', 'ru', 'de', 'it', 'gr', 'hu', 'id', 'my']

// 异步加载语言包
const loadLanguageAsync = async locale => {
    // 如果语言已经加载，直接返回
    if (loadedLanguages.includes(locale)) {
        return Promise.resolve(locale)
    }

    // 否则，尝试动态加载语言包
    try {
        const messages = await import(`./locales/${locale}.json`)
        i18n.global.setLocaleMessage(locale, messages.default)
        loadedLanguages.push(locale)
        return Promise.resolve(locale)
    } catch (e) {
        console.error(`Failed to load language: ${locale}`, e)
        return Promise.reject(e)
    }
}

/**
 * 配置i18n国际化
 * @type {import('vue-i18n').I18n}
 */
const i18n = createI18n({
    legacy: false,
    locale: encrypt.GetLocalData('locale') || 'zh',
    fallbackLocale: 'en',
    messages: {
        en,
        zh,
        jp,
        kr,
        es,
        fr,
        pt,
        ru,
        de,
        it,
        gr,
        hu,
        id,
        my,
        cz,
        nl,
        sa,
        th,
        tr,
        ua,
        vn,
        zh1
    },
    sync: true,
    silentTranslationWarn: true,
    missingWarn: false,
    fallbackWarn: false
})

export const setLocale = async locale => {
    try {
        await loadLanguageAsync(locale)
        i18n.global.locale.value = locale
        encrypt.SetLocalData('locale', locale)
        await nextTick()
        document.querySelector('html').setAttribute('lang', locale)
    } catch (e) {
        console.error(`Failed to set locale: ${locale}`, e)
    }
}

export default i18n
